package twentytwenty;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author: Zahi
 * @Description: 你可以假设数组是非空的，并且给定的数组总是存在多数元素。
 * @Date Created in 2020-12-05 12:56
 * @Modified By:
 */
public class MajorityElement_169 {
    public static void main(String [] args){
        int [] nums = new int[]{3,2,3};
        System.out.println(majorityElement(nums));
    }

    public static int majorityElement(int[] nums) {
        int length = nums.length;
        int over = length / 2;
        int change;
        // key为当前数字的值 value为该数字存在的对应的数量
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < length; i++) {
            int count = 1;
            change = nums[i];
            if (nums[i] == Integer.MAX_VALUE){
                continue;
            }
            for (int j = i + 1; j < length; j++) {
                if (nums[i] == nums[j]){
                    count ++;
                }
            }
            map.put(change,count);
            for (int j = 0; j < length; j++) {
                if (nums[j] == change){
                    nums[j] = Integer.MAX_VALUE;
                }
            }
        }
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            Integer key = entry.getKey();
            Integer value = entry.getValue();
            if (value > over) {
                return key;
            }
        }
        return nums[0];
    }
}
